package com.ricky.base.handler;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.ricky.base.bean.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Ricky
 * @date 2020-7-22 10:35
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ApiResult<Object> handlerMethodArgumentException(HttpServletRequest req, Exception e) {
        String errmsg = e.getMessage();

        if (errmsg == null) {
            Throwable cause = e.getCause();
            if (cause != null) {
                errmsg = cause.getMessage();
                if (!StringUtils.hasText(errmsg)) {
                    errmsg = cause.toString();
                }
                log.error("全局异常捕获：" + errmsg, cause);
            } else {
                errmsg = e.toString();
                log.error("全局异常捕获：" + errmsg, e);
            }
        } else {
            log.error("全局异常捕获：" + errmsg, e);
        }

        return ApiResult.fail(errmsg);
    }
}
